/*
 * @Author: modefy
 * @Date: 2021-12-06 10:13:57
 * @LastEditors: ZN
 * @LastEditTime: 2023-05-11 10:21:06
 * @Description: Description
 */
import { addSort, updateSort, deleteSortById, getSortList, uploadImg } from "api/sort";
import { toast } from 'utils/toast';
import { ref } from 'vue';

import Router from "router";

// ts 声明对象数组
export let tableData = ref(null) // 应该用rective
export let sortTotal = ref(0)

export const getSortLists = () => {
  getSortList().then(data => {
    console.log(data, "分类");
    if(data.code === 200){
      tableData.value = data.data.data.map(item => {
        let imgList: string[] = [];
        let showImgUrl = "";
        // 处理图片数组
        if(item.imgUrl && item.imgUrl !== ""){
          if(item.imgUrl.includes(',')){
            imgList = item.imgUrl.split(",");
            showImgUrl = imgList[0];
          }else {
            imgList.push(item.imgUrl);
            showImgUrl = item.imgUrl;
          }
        }
        item.imgList = imgList;
        item.showImgUrl = showImgUrl;
        return item
      });
      console.log(tableData.value, "tableData.value");
      sortTotal.value = data.data.total;
    }
  })
}


// 添加技术数据 业务代码（前后端对接层）
export const addTechSort = (data) => {
    console.log(data, "参数");
    if(data.sortName === ""){
        toast("请填写分类名称");
        return
    }
    addSort(data).then(data => {
      if(data.code === 200){
        toast(data.msg);
        Router.replace("/kld/sort")
      }else {
        toast(data.msg);
      }
    })
  }

  export const updateTechSort = (data) => {
    if(data.sortName === ""){
        toast("请填写分类名称");
        return
    }
    updateSort(data).then(data => {
      if(data.code === 200){
        toast(data.msg);
        Router.replace("/kld/sort")
      }else {
        toast(data.msg);
      }
    })
  }

  // 函数表达式
  export const deleteTechSortById = (id) =>{
    deleteSortById(id).then(data => {
      toast(data.msg);
      getSortLists();
    })
  }

  // 上传图片
  export const uploadImgs = async (data) => {
    return await uploadImg(data)
  }